package org.catpay.common.exception;

import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.catpay.common.utils.R;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;

import lombok.extern.slf4j.Slf4j;

/**
 * 异常处理器
 * 
 */

@ControllerAdvice
@Slf4j
public class RRExceptionHandler {

	/**
	 * 处理自定义异常
	 */
	@ExceptionHandler(RRException.class)
	@ResponseBody
	public R<?> handleRRException(RRException e) {
		return R.error(e.getCode()+"", e.getMessage());
	}


	@ExceptionHandler({ DuplicateKeyException.class })
	@ResponseBody
	public R<?> handleDuplicateKeyException(DuplicateKeyException e) {
		log.error(e.getMessage(), e);
		return R.error("数据库中已存在该记录");
	}

	@ExceptionHandler({ UnknownAccountException.class, LockedAccountException.class })
	@ResponseBody
	public R<?> handleUnknownAccountException(Exception e) {
		log.error(e.getMessage(), e);
		return R.error(e.getMessage());
	}

	@ExceptionHandler(AuthorizationException.class)
	@ResponseBody
	public R<?> handleAuthorizationException(AuthorizationException e) {
		log.error(e.getMessage(), e);
		return R.error("没有权限，请联系管理员授权");
	}

	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public R<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
		BindingResult bindingResult = e.getBindingResult();
		return R.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
	}
	@ExceptionHandler(IllegalArgumentException.class)
	@ResponseBody
	public R<?> handleIllegalArgumentException(IllegalArgumentException e) {

		return R.error(e.getMessage());
	}
	
	@ExceptionHandler(Exception.class)
	@ResponseBody
	public R<?> handleException(Exception e) {
		log.error(e.getMessage(), e);
		return R.error();
	}
}
